let that = this; //当前页面
let feedbackR, annunciateR; //两个容器
let layer;//弹出框
let feedbackE;//反馈列表
let annunciate;//公告列表
let idx;//弹出框
let hint; //提示框
layui.config({
    base: '../lay/dist/'
});
layui.use(['layer', 'form', 'miniTab','notice'], function () {
    let $ = layui.jquery,
        miniTab = layui.miniTab;
    layer = layui.layer
    form = layui.form; //只有执行了这一步，部分表单元素才会自动修饰成功
    miniTab.listen();
   hint =layui.notice;

    $(function () {
        // alert("加载")
        myChart.setOption(option)
        myChart2.setOption(option)
        myChart3.setOption(option)

        //        加载 反馈列表 和公告列表，
        feedbackR = $(".feedback_content");
        annunciateR = $(".annunciate_content")
        //公告  添加 删除  置顶
        $.post('/annunciate/search',{annTypeId:1,state:0,page:1,limit:10}, function (res) {
            console.log(res)
            annunciate = res.data;//填充值
            $.post('/annunciate/search',{annTypeId:2,state:0,page:1,limit:10}, function (res) {
               annunciate= annunciate.concat(res.data)
            that.showA(annunciate)
            })
        })
        // 反馈
        $.post('/feedback/all', function (res) {
            console.log("反馈", res)
            feedbackE = res.data;
            let i = 0;
            for (let e of feedbackE) {

                feedbackR.append("                        <div class=\"layuimini-notice\">\n" +
                    "                            <div class=\"layuimini-notice-title\">" + e.content + "</div>\n" +
                    "                            <div class=\"layuimini-notice-extra\">" + ConverterDate(e.createtime, 'yyyy-MM-dd HH:mm') + "</div>\n" +
                    "                        </div>")
                i++;
            }
            //    渲染反馈, 点击弹出框，显示反馈信息
        }, "json")

    });

    hint.options = {
        closeButton: true,//显示关闭按钮
        debug: false,//启用debug
        positionClass: "toast-bottom-right",//弹出的位置,
        showDuration: "300",//显示的时间
        hideDuration: "1000",//消失的时间
        timeOut: "2000",//停留的时间
        extendedTimeOut: "1000",//控制时间
        showEasing: "swing",//显示时的动画缓冲方式
        hideEasing: "linear",//消失时的动画缓冲方式
        iconClass: 'toast-info', // 自定义图标，有内置，如不需要则传空 支持layui内置图标/自定义iconfont类名
        onclick: null, // 点击关闭回调
    };
});


//渲染公告;
function showA(list) {
    annunciateR.html("")
    let i = 0;
    for (let l of list) {
        annunciateR.append('<div class="a_item"> <text>' + l.content + '\n</text>' +
            '                            <span class="buttons" data_index="' + i + '">\n' +
            '                            <button type="button" class="layui-btn layui-btn-sm layui-btn-primary"\n' +
            '                                    onclick="stickAnnunciate(this)">\n' +
            '                                <i class="layui-icon layui-icon-release"></i>置顶\n' +
            '                            </button>\n' +
            '                            <button type="button" class="layui-btn layui-btn-sm layui-btn-danger"\n' +
            '                                    onclick="delAnnunciate(this)">\n' +
            '                                <i class="layui-icon layui-icon-delete"></i> 删除\n' +
            '                            </button>\n' +
            '                                </span>\n' +
            '                        </div>')
        i++;
    }
}

//点击显示添加公告
function addAnnunciate() {
    // alert("添加公告")
    idx = layer.open({
        title: '添加公告',
        type: 1,
        offset: 100,
        shade: 0.2,
        maxmin: false,
        shadeClose: true,
        area: ['50%', '40%'],
        content: $("#addA"),
    });
}

//添加公告
function addA() {
    let formData = form.val("form");
    let content = $("#annunciateContent").val();
    let type=formData.type?1:2;
    $.post("/annunciate/add", {"content": formData.content, "annTypeId": type,"state":0}, function (res) {
        if (res.success) {
            hint.success("添加成功")
            annunciate.push({id: res.data, content: content, annTypeId: type});//数组追加
            layer.close(idx)
            showA(annunciate)//重新渲染数据
        } else {
            // layer.msg("添加失败" + res.msg);
            hint.error("添加失败"+res.data)
        }
        //清空内容
        $("#annunciateContent").val("")
    })
}

//删除公告
function delAnnunciate(obj) {
    // alert("删除公告")
    let index = parseInt($(obj).parent().attr("data_index"));
    let id = annunciate[index].id;
   idx= layer.confirm('真的要删除此公告?', function () {
        console.log(id)
        console.log(annunciate)
        $.post('/annunciate/del', {'id': id,}, function (rst) {
            if (rst.success) {
                // layer.msg("删除成功:");
                hint.success("删除成功")
                //    删除数组 然后渲染
                annunciate.splice(index, 1);
                showA(annunciate)
            } else {
                hint.error("删除失败")
                // layer.msg("删除失败" + rst.msg)
            }
            layer.close(idx);
        })
    });
    // alert("删除公告")
}

//置顶公告
function stickAnnunciate(obj) {
    let index = parseInt($(obj).parent().attr("data_index"));
    //拿到那个idnex
    // alert("置顶公告")
    let ann = annunciate[index];
    console.log("元素",ann,"集合",annunciate,"下标:",index)
    // return
    $.post('/annunciate/stick', {'id': ann.id,}, function (rst) {
        if (rst.success) {
            // layer.msg("公告置顶成功:");
            hint.success("公告置顶成功")
            //    修改位置，然后渲染
            annunciate.splice(index, 1);
            annunciate.unshift(ann);
            showA(annunciate)
        } else {
            // layer.msg("公告置顶失败" + rst.msg)
            hint.error("公告置顶失败,请稍后重试。")
            }
        // layer.close(idx);
    })
}

let color = ['rgb(55, 162, 218)', 'rgb(251, 114, 147)', 'rgb(231, 188, 243)',
    'rgb(50, 197, 233)', 'rgb(103, 224, 227)', 'rgb(159, 230, 184)',
    "rgb(255, 219, 92)", 'rgb(224, 98, 174)'];
// 统计图
let myChart = echarts.init(document.getElementById('echarts-records'));
let myChart2 = echarts.init(document.getElementById('echarts-records2'));
let myChart3 = echarts.init(document.getElementById('echarts-records3'));
let data = genData(4);
let option = {
    title: {
        text: '学社总计',
        subtext: '最新学社信息',
        left: 'center'
    },
    tooltip: {
        trigger: 'item',  //触发类型。
        showContent: true, //提示框浮层    series    name=a  data=c   xAxis =b
        //  饼图、仪表盘、漏斗图: {a}（系列名称），{b}（数据项名称name），{c}（数值 value）, {d}（百分比）
        formatter: '  a: {a}<br/> b: {b}</br> c:{c} ({d}) '
    },
    series: [
        {
            name: "名字", //a
            type: 'pie',
            radius: '55%',
            center: ['40%', '50%'],
            data: data.seriesData, // 图表信息
            emphasis: {
                itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'  //选中颜色
                }
            }
        },
    ],
    color: randColor(5)
};

function randColor(len) {
    let c = [];
    for (let i = 0; i < len; i++) {
        c.push(color[Math.floor(Math.random() * color.length)])
    }
    return c;
}

//获取随机性氏
function genData(count) {
    let nameList = [
        '赵', '钱', '孙', '李', '周', '吴', '郑', '王', '冯', '陈', '褚', '卫', '蒋', '沈', '韩', '杨', '朱', '秦', '尤', '许', '何', '吕', '施', '张', '孔', '曹', '严', '华', '金', '魏', '陶', '姜', '戚', '谢', '邹', '喻', '柏', '水', '窦', '章', '云', '苏', '潘', '葛', '奚', '范', '彭', '郎', '鲁', '韦', '昌', '马', '苗', '凤', '花', '方', '俞', '任', '袁', '柳', '酆', '鲍', '史', '唐', '费', '廉', '岑', '薛', '雷', '贺', '倪', '汤', '滕', '殷', '罗', '毕', '郝', '邬', '安', '常', '乐', '于', '时', '傅', '皮', '卞', '齐', '康', '伍', '余', '元', '卜', '顾', '孟', '平', '黄', '和', '穆', '萧', '尹', '姚', '邵', '湛', '汪', '祁', '毛', '禹', '狄', '米', '贝', '明', '臧', '计', '伏', '成', '戴', '谈', '宋', '茅', '庞', '熊', '纪', '舒', '屈', '项', '祝', '董', '梁', '杜', '阮', '蓝', '闵', '席', '季', '麻', '强', '贾', '路', '娄', '危'
    ];
    let legendData = [];
    let seriesData = [];
    let selected = {};
    for (let i = 0; i < count; i++) {
        let name = Math.random() > 0.65
            ? makeWord(4, 1) + '·' + makeWord(3, 0)
            : makeWord(2, 1);
        legendData.push(name);
        seriesData.push({
            name: name,
            value: Math.round(Math.random() * 100000),
        });
        selected[name] = i < 6;
    }

    return {
        legendData: legendData,
        seriesData: seriesData,
        selected: selected
    };

    function makeWord(max, min) {
        let nameLen = Math.ceil(Math.random() * max + min);
        let name = [];
        for (let i = 0; i < nameLen; i++) {
            name.push(nameList[Math.round(Math.random() * nameList.length - 1)]);
        }
        return name.join('');
    }
}

function closeBox() {
    layer.close(idx)
    // alert("取消添加")
}
